package BaseService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"net/url"
)

func getShareToPath(typeStr string) string {
	switch typeStr {
	case "tuanShare":
		return "/pages/goods/tuanDetails"
	case "goodsShare":
		return "/pages/goods/details"
	}
	return ""
}
func GetShareUrl(ctx context.Context, typeStr string, parames g.MapStrStr) string {
	params := url.Values{}
	for k, v := range parames {
		params.Add(k, v)
	}
	pagePath := getShareToPath(typeStr) + "?" + params.Encode()
	shareUrl := gmd5.MustEncrypt(pagePath)
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "share_url").Where("type", typeStr).Where("share_url", shareUrl).
		Where("status", 1).Fields("1").Count()
	if err != nil {
		return ""
	}
	shareUrlProfix := g.Cfg().GetString("site.ShareUrlProfix")
	if count > 0 {
		return shareUrlProfix + shareUrl
	}
	// 入库，转换成短链接
	_, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "share_url").Data(g.Map{
		"type":      typeStr,
		"share_url": shareUrl,
		"page_path": pagePath,
	}).Save()
	if err != nil {
		return ""
	}
	return shareUrlProfix + shareUrl
}
